<template>
  <div class="plan-page">
    <div class="plan-header">
      <div class="left">
        <img src="@/assets/image/form/header-info.png" alt="">
        方案详情
      </div>
      <div class="right">
        <el-button :icon="Promotion" @click="goBackLast">返回</el-button>
      </div>

    </div>
    <div class="plan-detail">
      <el-scrollbar style="height:100%">
        <el-button :icon="CirclePlus" type="primary" @click="addTask">新建</el-button>
        <div class="task-group">
          <div class="task-item" v-for="(option,index) in reactiveData.taskList" :key="index">
            <div class="task-item-header el-row">
              <div class="index-bg">{{index+1}}</div>
              <div class="el-col-4 el-col-offset-1">
                <img :src="getImage(`table/${option.statusName ? option.statusName : '待编制方案'}.png`)">
                <img v-show="option.statusName==='待执行' || option.statusName==='进行中'" src="@/assets/image/table/ic_jiance.png" alt="" style="margin-left:15px; cursor: pointer;" @click="showDeviceInfo(index)">
                <img src="@/assets/image/table/track.png" alt="" style="margin-left:15px; cursor: pointer;" @click="showTrack(option.tbTaskUavList)">
              </div>
              <div class="el-col-8 el-col-offset-1">
                （预计）执行时间 : {{option.arrTime[0] || ''}} - {{option.arrTime[1] || ''}}
              </div>
              <div class="handle-bar el-col-8  el-col-offset-1">
                <el-button type="primary" @click="delOneTaskPlans(option.id,index)">删除执行</el-button>
                <el-button type="primary" @click="overOneTaskPlan(option.id)" :disabled="!option.statusName">结束执行</el-button>
                <el-button type="primary" @click="changeShowUpload(option.id,index)" :disabled="option.statusName!=='已完成'">成果上传</el-button>
                <img :src="getImage(`table/${option.isDetail ?'on':'off'}.png`)" alt="" @click="changeDetail(index)">
              </div>
            </div>

            <div class="task-item-content" v-show="option.isDetail">
              <el-form :ref="(el: FormInstance) => { if (el) planFormRef[index] = el }" :model="option" :rules="planRules" label-width="150px" class="el-row">
                <el-form-item label="执行周期" prop="arrTime" class="el-col-23">
                  <el-date-picker :disabled="option.statusName==='进行中'||option.statusName==='已完成'" style="width:100%" clearable v-model="option.arrTime" :disabled-date="disabledDate" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
              </el-form>
              <div class="add-device">
                <h2>设备信息</h2>
                <el-button type="primary" @click="addOneDevice(listFormRefs[index],index)" v-show="option.statusName!=='进行中'&&option.statusName!=='已完成'">增加设备</el-button>
              </div>
              <el-form :ref="(el: FormInstance) => { if (el) listFormRefs[index] = el }" v-for="(uav,uavIndex) in option.tbTaskUavList" :model="uav" :key="uavIndex" :rules="uavRules" label-width="150px" style="width: 100%;" class="el-row tb-uav">
                <el-form-item label-width="0" class="el-col-3 el-col-offset-21" v-show="uavIndex > 0">
                  <el-button type="danger" @click="deleteOneDevice(index,uavIndex)"> 删除当前设备 </el-button>
                </el-form-item>
                <el-form-item label="设备" prop="uavSn" class="el-col-11">
                  <el-select v-model="uav.uavSn" style="width:100%" @visible-change="(val:boolean) =>{openchangeDevice(val,option.arrTime,index)}" :disabled="option.statusName==='进行中'||option.statusName==='已完成'">
                    <el-option v-for="(device,i) in reactiveData.deviceData" :key="i" :label="device.deviceSn" :value="device.deviceSn">

                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="飞手" prop="flyHandNameList" class="el-col-11 el-col-offset-1">
                  <el-select v-model="uav.flyHandNameList" multiple style="width:100%" @change="selectFlyer(uav.flyHandNameList,index,uavIndex)" :disabled="option.statusName==='进行中'||option.statusName==='已完成'">
                    <el-option v-for="(flyer,i) in reactiveData.flyerList" :key="i" :label="flyer.name" :value="`${flyer.name},${flyer.postCode}`">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="测区" prop="planList" class="el-col-11">
                  <el-select v-model="uav.planList" multiple style="width:100%" @change="selectArea(uav.planList,index,uavIndex)" :disabled="option.statusName==='进行中'||option.statusName==='已完成'">
                    <el-option v-for="(cequOption,i) in reactiveData.cequOptions" :key="i" :label="cequOption.name" :value="cequOption.id">
                      <span style="float: left">{{ cequOption.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 12px">已选择：{{ cequOption.surveyNum }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="el-col-11 el-col-offset-1" v-show="uav&&uav.id&&type === 'XCXJ'">
                  <el-button @click="addErrMsg(uav.id,option.id)">标记异常</el-button>
                </el-form-item>
              </el-form>
              <div class="save-device">
                <el-button type="primary" @click="saveOnePlan(planFormRef[index],index)" v-show="option.statusName!=='进行中'&&option.statusName!=='已完成'">保存方案</el-button>
              </div>
            </div>

            <div class="upload-table" v-show="option.showUpload">
              <h2 style="margin-bottom:1rem;">成果上传</h2>
              <el-table :data="option.uploadTable" border :span-method="objectSpanMethod" :header-cell-style="{  'font-size': '1rem',  'height':'3rem',  'background': '#E5EBF3 !important',  'color': '#333333',  }" height="300">
                <el-table-column prop="uavsn" label="设备" width="200" v-if="type === 'XCXJ'"> </el-table-column>
                <el-table-column prop="surveyname" label="区域名称" width="300" v-if="type === 'SJCJ'"> </el-table-column>
                <el-table-column prop="name" label="数据类型" width="120"> </el-table-column>
                <el-table-column>
                  <template #default="scope">
                    <el-upload v-if="type === 'XCXJ'" v-model:file-list="scope.row.uploadList" multiple :before-upload="beforeUpload" :on-remove="handleRemove">
                      <el-button type="primary" @click="setUpload(scope.row)">点击上传</el-button>
                    </el-upload>
                    <el-input v-else v-model="scope.row.content"></el-input>
                  </template>
                </el-table-column>
              </el-table>
              <div class="save-device">
                <el-button @click="saveUpload(option.uploadTable)" type="primary">上传成果</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <check-device v-if="deviceDialogVisible" @close="closeDevice" :deviceData="reactiveData.checkDeviceData"></check-device>
    <track-vue v-if="trackVisible" @close="coloseTrack" :trackData="reactiveData.trackData"></track-vue>
  </div>
</template>

<script setup lang=ts>
import { Promotion, CirclePlus } from "@element-plus/icons-vue";
import type {
  FormRules,
  FormInstance,
  UploadProps,
  TableColumnCtx,
} from "element-plus";
import { ElMessage } from "element-plus";

import { ref, reactive, onBeforeUpdate, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import router from "@/router";

import {
  getTaskPlanBYTaskId,
  getSurveyExecCount,
  getFlyer,
  getDeviceUav,
  saveTaskPlans,
  getNoConflictUav,
  newTaskPlan,
  delTaskPlans,
  overTaskPlan,
  getPlansResult,
  uploadFIle,
  saveTaskAchievement,
  addUavAlarm,
} from "@/api/task";
import { getImage } from "@/utils/util";

import checkDevice from "../checkDevice/device.vue";
import trackVue from "../track/track.vue";
import { da } from "node_modules/element-plus/es/locale";

const route = useRoute();
const planFormRef: any = ref([]);
const listFormRefs: any = ref([]);

let deviceDialogVisible = ref(false);
let trackVisible = ref(false);

const closeDevice = () => {
  deviceDialogVisible.value = false;
};

const coloseTrack = () => {
  trackVisible.value = false;
};

const disabledDate = (time: Date) => {
  // return time.getTime() < Date.now() - 3600 * 1000 * 24;
};

const showTrack = (data: any) => {
  trackVisible.value = true;
  reactiveData.trackData = data;
};

onBeforeUpdate(() => {
  planFormRef.value = [];
  listFormRefs.value = [];
});

let id = ref("");
let type = ref("");
let reactiveData: any = reactive({
  taskList: [],
  handleObj: [],
  cequOptions: [],
  flyerList: [],
  deviceData: [],
  uploadTypeData: {},
  checkDeviceData: [],
  trackData: [],
});

//检查设备
const showDeviceInfo = (index: number) => {
  reactiveData.checkDeviceData = reactiveData.handleObj[index];
  deviceDialogVisible.value = true;
};

interface SpanMethodProps {
  rowIndex: number;
  columnIndex: number;
}

const objectSpanMethod = ({ rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

//新增一个
const addTask = async () => {
  const res: any = await newTaskPlan({
    taskId: id.value,
  });
  if (res.statusCode === 200) {
    getTaskData();
  }
};

const planRules = reactive<FormRules>({
  arrTime: [{ required: true, message: "请选择期望执行时间" }],
});

const uavRules = reactive<FormRules>({
  uavSn: [{ required: true, message: "请选择设备", trigger: "change" }],
  flyHandNameList: [
    { required: true, message: "请选择执飞人员", trigger: "change" },
  ],
  planList: [{ required: true, message: "请选择测区", trigger: "change" }],
});

const changeDetail = (index: number) => {
  if (reactiveData.taskList[index] && reactiveData.taskList[index].isDetail) {
    reactiveData.taskList[index].isDetail = false;
    reactiveData.taskList[index].showUpload = false;
  } else {
    reactiveData.taskList[index].isDetail = true;
  }
};

const changeShowUpload = async (id: string, index: number) => {
  if (reactiveData.taskList[index] && reactiveData.taskList[index].showUpload) {
    reactiveData.taskList[index].showUpload = false;
  } else {
    if ((reactiveData.taskList[index].isDetail = true)) {
      reactiveData.taskList[index].showUpload = true;
    }
    const res: any = await getPlansResult({
      type: type.value,
      planId: id,
    });
    if (res.statusCode === 200) {
      reactiveData.taskList[index].uploadTable = [];
      reactiveData.taskList[index].uploadTable = res.data.map((item: any) => {
        return {
          ...item,
          uploadList: setUploadList(item.content),
        };
      });
    } else {
      reactiveData.uploadTable = [];
    }
  }
};

const setUploadList = (data: string) => {
  let arr: any[] = [];
  if (data && data.length > 0) {
    let dataArr = data.split(",");
    arr = dataArr.map((item: any) => {
      return {
        name: item,
        status: "success",
      };
    });
  }
  return arr;
};

const saveUpload = async (data: any) => {
  if (type.value === "XCXJ") {
    data.forEach((obj: any) => {
      obj.content = "";
      obj.uploadList.forEach((item: any, index: number) => {
        if (index === 0) {
          obj.content = item.name;
        } else {
          obj.content += "," + item.name;
        }
      });
    });
  }
  const res: any = await saveTaskAchievement(data);
  if (res.statusCode === 200) {
    getTaskData();
    ElMessage({
      message: "保存成果成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "保存成果失败",
      type: "warning",
    });
  }
};

const goBackLast = () => {
  router.push({
    path: "/home/task/patrolInspection",
  });
};

//获取测区
const getSurveyExecCountData = async () => {
  const res: any = await getSurveyExecCount({
    taskId: id.value,
  });
  if (res.statusCode === 200) {
    reactiveData.cequOptions = res.data;
  } else {
    reactiveData.cequOptions = [];
  }
};

const openchangeDevice = (val: boolean, data: any[], index: number) => {
  if (val) {
    changeDevice(data, index);
  }
};

//根据时间获取设备
const changeDevice = async (data: any[], index: number) => {
  if (data[0] && data[1]) {
    const res: any = await getNoConflictUav({
      startTime: data[0],
      endTime: data[1],
    });
    if (res.statusCode === 200) {
      reactiveData.deviceData = res.data;
    } else {
      reactiveData.deviceData = [];
    }
  } else {
    ElMessage({
      message: "请先选择好执行时间",
      type: "warning",
    });
  }
};

//获取方案详情
const getTaskData = async () => {
  const res: any = await getTaskPlanBYTaskId({
    taskId: id.value,
  });
  if (res.statusCode === 200) {
    reactiveData.taskList = [];
    reactiveData.handleObj = res.data;
    reactiveData.handleObj.forEach((item: any) => {
      let tbTaskUavList: any[] = [];
      if (item.tbTaskUavList.length === 0) {
        tbTaskUavList.push({
          id: "",
          uavSn: "",
          flyHandNameList: [],
          planList: [],
        });
      } else {
        item.tbTaskUavList.forEach((task: any) => {
          tbTaskUavList.push({
            id: task.id,
            uavSn: task.uavSn,
            flyHandNameList: setFlyData(task.flyHandName, task.flyHandCode),
            planList: setCequOptionList(task.planSurveyList),
          });
        });
      }
      let obj = {
        id: item.id,
        statusName: item.statusName,
        arrTime: [item.startTime, item.endTime],
        tbTaskUavList: tbTaskUavList,
        resultUpload: item.resultUpload,
      };
      reactiveData.taskList.push(obj);
    });
  } else {
    reactiveData.handleObj = [];
  }
};

//删除一个方案
const delOneTaskPlans = async (id: string, index: number) => {
  const res: any = await delTaskPlans({
    planId: id,
  });
  if (res.statusCode === 200) {
    reactiveData.taskList.splice(index, 1);
    getTaskData();
    ElMessage({
      message: "删除执行成功",
      type: "success",
    });
  }
};

//结束一个方案
const overOneTaskPlan = async (id: string) => {
  const res: any = await overTaskPlan({
    planId: id,
  });
  if (res.statusCode === 200) {
    getTaskData();
    ElMessage({
      message: "结束执行成功",
      type: "success",
    });
  }
};

//上传
const beforeUpload: UploadProps["beforeUpload"] = async (file) => {
  let data = reactiveData.uploadTypeData;
  let fileType = file.name.substring(file.name.lastIndexOf("."));

  let fileData = [
    {
      fater: "IMG",
      son: [".jpg", ".png", ".jpeg"],
    },
    {
      fater: "VIDEO",
      son: [".mp4"],
    },
  ];
  for (let fi in fileData) {
    if (fileData[fi].fater === data.datatype) {
      let isNext = false;
      if (data.datatype === fileData[fi].fater) {
        for (let i in fileData[fi].son) {
          if (fileType === fileData[fi].son[i]) {
            isNext = true;
            break;
          }
        }
      }
      if (!isNext) {
        ElMessage({
          message: `仅限上传${data.name}文件`,
          type: "warning",
        });
        return false;
      }
    }
  }
  let formData = new FormData();
  formData.append("file", file);
  const res: any = await uploadFIle(formData);
  if (res.statusCode === 200) {
    ElMessage({
      message: "上传成功",
      type: "success",
    });
    reactiveData.uploadTypeData.uploadList.push({
      name: res.data,
      status: "success",
    });
  } else {
    ElMessage({
      message: res.message,
      type: "warning",
    });
  }
  return false;
};

const setUpload = (data: any) => {
  reactiveData.uploadTypeData = data;
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

//设置测区回显
const setCequOptionList = (data: any[]) => {
  let arr: string[] = [];
  data.forEach((item: any) => {
    arr.push(item.surveyId);
  });
  return arr;
};

//设置飞行人员回显
const setFlyData = (fly: string, code: string) => {
  let arr: string[] = [];
  if (fly && code) {
    let flyArr = fly.split(",");
    let codeArr = code.split(",");
    flyArr.forEach((item: any, index: number) => {
      arr.push(flyArr[index] + "," + codeArr[index]);
    });
  }
  return arr;
};

//获取飞手信息
const getFlyerData = async () => {
  const res: any = await getFlyer({
    postName: "飞手",
  });
  if (res.statusCode === 200) {
    reactiveData.flyerList = res.data;
  } else {
    reactiveData.flyerList = [];
  }
};

//获取设备列表
const getDeviceUavData = async () => {
  const res: any = await getDeviceUav({
    deviceType: "经纬M300RTK",
  });
  if (res.statusCode === 200) {
    reactiveData.deviceData = res.data;
  } else {
    reactiveData.deviceData = [];
  }
};

//增加一个设备
const addOneDevice = (formEl: FormInstance | undefined, index: number) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      reactiveData.taskList[index].tbTaskUavList.push({
        uavSn: "",
        flyHandNameList: [],
        planList: [],
      });
      reactiveData.handleObj[index].tbTaskUavList.push({});
    } else {
      ElMessage({
        message: "请填完上一个设备表单",
        type: "warning",
      });
    }
  });
};

//选择飞手
const selectFlyer = (data: any, index: number, uavIndex: number) => {
  if (reactiveData.handleObj[index].tbTaskUavList.length > 0) {
    reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandName = "";
    reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandCode = "";
  } else {
    reactiveData.handleObj[index].tbTaskUavList.push({
      flyHandName: "",
      flyHandCode: "",
      planSurveyList: [],
    });
  }

  data.forEach((item: any, i: number) => {
    if (i === 0) {
      reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandName =
        item.split(",")[0];
      reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandCode =
        item.split(",")[1];
    } else {
      reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandName =
        reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandName +
        "," +
        item.split(",")[0];
      reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandCode =
        reactiveData.handleObj[index].tbTaskUavList[uavIndex].flyHandCode +
        "," +
        item.split(",")[1];
    }
  });
};

//添加异常信息
const addErrMsg = async (uavId: string, planId: string) => {
  const res: any = await addUavAlarm({
    taskId: id.value,
    uavId,
    planId,
  });
  if (res.statusCode === 200) {
    ElMessage({
      message: "标记异常成功",
      type: "success",
    });
  } else {
  }
};

//选择测区
const selectArea = (data: any, index: number, uavIndex: number) => {
  if (reactiveData.handleObj[index].tbTaskUavList.length > 0) {
    reactiveData.handleObj[index].tbTaskUavList[uavIndex].planSurveyList = [];
  } else {
    reactiveData.handleObj[index].tbTaskUavList.push({
      flyHandName: "",
      flyHandCode: "",
      planSurveyList: [],
    });
  }
  data.forEach((item: any, i: number) => {
    for (let ci in reactiveData.cequOptions) {
      if (reactiveData.cequOptions[ci].id === item) {
        reactiveData.handleObj[index].tbTaskUavList[
          uavIndex
        ].planSurveyList.push({
          planId: reactiveData.handleObj[index].id,
          surveyId: item,
          taskId: id.value,
        });
      }
    }
  });
};

//保存方案
const saveOnePlan = (formEl: FormInstance | undefined, index: number) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let data = reactiveData.taskList[index];
      reactiveData.handleObj[index].startTime = data.arrTime[0];
      reactiveData.handleObj[index].endTime = data.arrTime[1];

      reactiveData.taskList[index].tbTaskUavList.forEach(
        (item: any, i: number) => {
          if (!reactiveData.handleObj[index].tbTaskUavList[i]) {
            reactiveData.handleObj[index].tbTaskUavList[i] = {};
          }
          reactiveData.handleObj[index].tbTaskUavList[i].uavSn = item.uavSn;
          reactiveData.handleObj[index].tbTaskUavList[i].startTime =
            data.arrTime[0];
          reactiveData.handleObj[index].tbTaskUavList[i].endTime =
            data.arrTime[1];
          reactiveData.handleObj[index].tbTaskUavList[i].taskId = id.value;
        }
      );
      const res: any = await saveTaskPlans([reactiveData.handleObj[index]]);
      if (res.statusCode === 200) {
        getTaskData();
        ElMessage({
          message: "保存成功",
          type: "success",
        });
      }
    } else {
      ElMessage({
        message: "请确定表单是否填写完整",
        type: "warning",
      });
    }
  });
};

const deleteOneDevice = (index: number, uavIndex: number) => {
  reactiveData.taskList[index].tbTaskUavList.splice(uavIndex, 1);
  reactiveData.handleObj[index].tbTaskUavList.splice(uavIndex, 1);
};

if (route && route.query.id) {
  id.value = route.query.id as string;
  type.value = route.query.type as string;
  getTaskData();
  getSurveyExecCountData();
}
getFlyerData();
getDeviceUavData();
</script>

<style lang='less'>
.plan-page {
  height: 100%;
  width: 100%;
  .plan-header {
    width: 98%;
    height: 30px;
    padding: 20px 1%;
    background: #f9fcff;
    box-shadow: 0px 0px 20px 5px #a5bbdc;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
    }
  }
  .plan-detail {
    margin-top: 30px;
    width: 96%;
    height: 690px;
    padding: 20px 2%;
    background: #f9fcff;
    box-shadow: 0px 0px 20px 5px #a5bbdc;
    border-radius: 5px;
    .task-group {
      margin-top: 15px;
      .task-item {
        margin-bottom: 20px;
        .task-item-header {
          background-color: #e5ebf3;
          padding: 20px 15px;
          font-size: 16px;
          color: #333;
          .index-bg {
            height: 32px;
            width: 32px;
            background-color: rgba(72, 140, 255, 0.2);
            border-radius: 50%;
            font-family: Akrobat-Bold, Akrobat;
            font-weight: bold;
            color: #488cff;
            line-height: 30px;
            text-align: center;
          }
          .handle-bar {
            text-align: right;
            img {
              margin-left: 30px;
              cursor: pointer;
            }
          }
        }
        .upload-table {
          padding: 15px 4%;
        }
        .task-item-content {
          margin-top: 20px;
          .add-device {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 0 4%;
          }

          .tb-uav {
            padding: 15px 0;
            border-bottom: 1px solid #ccc;
          }
        }
        .save-device {
          text-align: center;
          margin: 15px 0;
        }
      }
    }
  }
}
</style>